package org.vectrics.cms;

import java.io.FileOutputStream;
import java.io.InputStream;

import javax.servlet.jsp.JspException;

import org.apache.log4j.Category;
import org.apache.struts.upload.FormFile;
import org.vectrics.SystemException;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.struts.VectricsStrutsAction;


public class UploadImageAction extends VectricsStrutsAction {
    private static Category log = Category.getInstance(UploadImageAction.class);
	public static String USER_ID_PARAM = "userId";

	// Intercept 
	protected String doExecute(VectricsActionData actionData)	throws JspException {
		boolean illegalFileType = false;
		UploadImageForm form = (UploadImageForm)actionData.getForm();
		
		FormFile formFile = form.getTheFile();
		
		String fileName = formFile.getFileName();
		log.info("execute() - uploading image");
		log.info("File Name = " + fileName);
		log.info("File Size = " + formFile.getFileSize());
		
		if (formFile.getFileSize() > 600000) {
			throw new SystemException("Image too large to upload!  Size = " + formFile.getFileSize() + " bytes");
		}
		
		String ext = "doc";
		if (fileName.endsWith("gif")) {
			ext = "gif";
		}
		else if (fileName.endsWith("png")) {
			ext = "png";
		}
		else if (fileName.endsWith("jpeg")) {
			ext = "jpg";
		}
		else if (fileName.endsWith("jpg")) {
			ext = "jpg";
		}
		else {
			illegalFileType = true;
		}

		
		if (!illegalFileType) {
			try {
				ContentHelper helper = new ContentHelper();
				String cmsFilePath = helper.getContentFileName(ThreadProperties.getDomain(), form.getSection(), form.getCode()); 
					
				FileOutputStream file = new FileOutputStream(cmsFilePath);
				InputStream uploadStream = formFile.getInputStream();
				
				boolean done = false;
				while (!done) {
					int r = uploadStream.read();
					if (r < 0) {
						done = true;
					} else {
						file.write(r);
					}
				}
				file.close();
				uploadStream.close();
				
			} catch (Exception ex) {
				
			}
			return "success";
		} else {
			return "illegalfile";
		}
		
		
	 }
	
}
